package com.plian.system.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.plian.Tools.TokenUtil;
import com.plian.Tools.Tools;
import com.plian.Tools.UuidUtil;
import com.plian.Tools.pagedata.PageData;
import com.plian.Tools.pagedata.UserData;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.config.exception.SecureException;
import com.plian.system.config.exception.TokenException;
import com.plian.system.dao.bt.loginfo.LogInfoDao;
import com.plian.system.dao.sys.user.UserDao;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ObjResult;
import com.plian.system.model.token.PassToken;
import com.plian.system.service.sys.orgzation.OrgzationService;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

@Component
@Log4j2
public class Interceptor implements HandlerInterceptor {
    @Autowired
    UserDao userDao;
    @Autowired
    LogInfoDao logInfoDao;
    @Autowired
    OrgzationService orgzationService;

    /**
     * 进入controller方法之前调用
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");// 从 http 请求头中取出 token
        if (Tools.isEmpty(token)) {
            token = request.getParameter("token");
        }
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Class<?> clazz = handlerMethod.getBeanType();
        if (clazz.getName().equals("springfox.documentation.swagger.web.ApiResourceController")) {
            return true;
        }
        if (clazz.isAnnotationPresent(PassToken.class)) {
            PassToken annotation = clazz.getAnnotation(PassToken.class);
            if (annotation.required()) {
                return true;
            }
        }
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注解，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }

        if ("/error".equals(request.getRequestURI())) {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                requestAttributes.setAttribute("LOG_OPERATION_VALUE", "token验证", RequestAttributes.SCOPE_REQUEST);
            }
            throw new MyRuntimeException(new ObjResult(CommonCode.ERROR));
        }
        //判断有无Token
        if (Tools.isEmpty(token)) {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                requestAttributes.setAttribute("LOG_OPERATION_VALUE", "token验证", RequestAttributes.SCOPE_REQUEST);
            }
            throw new TokenException(CommonCode.UNTOKEN);
        }
        // 获取 token 中的 user id
        List<String> Audience;
        try {
            Audience = JWT.decode(token).getAudience();
        } catch (JWTDecodeException e) {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                requestAttributes.setAttribute("LOG_OPERATION_VALUE", "token验证", RequestAttributes.SCOPE_REQUEST);
            }
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new TokenException(CommonCode.UNTOKEN);
        }
        if (Audience == null || Audience.size() <= 0) {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                requestAttributes.setAttribute("LOG_OPERATION_VALUE", "token验证", RequestAttributes.SCOPE_REQUEST);
            }
            throw new SecureException(CommonCode.UNAUTHORISE);
        }
        String userid = Audience.get(0);
        PageData user = userDao.findbyid(userid);
        if (user == null) {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                requestAttributes.setAttribute("LOG_OPERATION_VALUE", "token验证", RequestAttributes.SCOPE_REQUEST);
            }
            throw new TokenException(CommonCode.UNTOKEN);
        }
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getString("password"))).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            if (requestAttributes != null) {
                requestAttributes.setAttribute("LOG_OPERATION_VALUE", "token验证", RequestAttributes.SCOPE_REQUEST);
            }
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new TokenException(CommonCode.UNTOKEN);
        }
        log.info("----调用开始------");
        log.info("调用接口:" + request.getRequestURI());
        log.info("请求方式:" + request.getMethod());
        log.info("IP:" + request.getRemoteAddr());
        log.info("操作用户:" + user.getString("username"));
        log.info("操作用户Id:" + user.getString("id"));
        log.info("请求时间:" + Tools.date2Str(new Date()));
//            RequestWrapper requestWrapper=new RequestWrapper(request);
//            log.info("参数:"+requestWrapper.getBody());

//       if(!"/error".equals(request.getRequestURI())){
//           PageData pageData = new PageData();
//           pageData.put("id", UuidUtil.get32UUID());
//           pageData.put("callingInterface",request.getRequestURI());
//           pageData.put("requestWay",request.getMethod());
//           pageData.put("ip",request.getRemoteAddr());
//           pageData.put("userName",user.getString("name"));
//           pageData.put("userId",user.getString("id"));
//           pageData.put("requestTime",Tools.date2Str(new Date()));
//           logInfoDao.save(pageData);
//       }

        UserData userData = new UserData();
        if (Audience.size() == 2) {
            userData.setOrgId(Audience.get(1));
            userData.setCompetentOrganization(orgzationService.getCompetentOrganization(Audience.get(1)));
        }
        userData.setUserId(userid);
        userData.setUserName(user.getString("username"));
        userData.setRealName(user.getString("name"));
        userData.setOfficeId(user.getString("officeId"));
        TokenUtil.setUserData(userData);
        return true;
    }

    /**
     * controller方法结束之后调用如果有controller方法有异常则不会调用
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        TokenUtil.clearUserData();
        log.info("----调用结束-----");
    }

    /**
     * controller方法之后调用
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

    private String getBody(HttpServletRequest request) {
        String body = "";
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            } else {
                stringBuilder.append("");
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error(ExceptionUtils.getFullStackTrace(e));
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    log.error(ExceptionUtils.getFullStackTrace(e));
                }
            }
        }
        body = stringBuilder.toString();
        return body;
    }
}
